const {getAuthorityList, newAuthority, delAuthority, getAuthorityDetail} = require("../controller/authority");
const Response = require('../common/Response')
const router = require('koa-router')()

router.prefix('/api/authority')

// 获取权限列表
router.get('/list', async (context, next) => {
  const rights = await getAuthorityList()
  let right = [
    {id: 1, children: [] },
    {id: 2, children: [] },
    {id: 3, children: [] },
  ]
  right.forEach(item => {
    item.children = rights.filter(ele => ele.role_id === item.id && ele.level === 0);
    item.children.forEach(sub => {
      sub.children = rights.filter(thr => thr.pid === sub.id && thr.level === 1);
    })
  })
  context.body = Response.success(right)
})
// 仅获取权限
router.get('/list/only', async (context, next) => {
  const rights = await getAuthorityList()
  context.body = Response.success(rights)
})
// 角色新增权限（实现多个权限的更新）
router.post('/new', async (context, next) => {
  const val = await newAuthority(context.request.body)
  if (!val) {
    context.body = Response.failure(`添加权限失败`)
  } else {
    context.body = Response.success(`添加权限成功`)
  }
})
// 删除角色权限
router.post('/del', async (context, next) => {
  const val = await delAuthority(context.request.body)
  if (val) {
    context.body = Response.success('删除权限成功')
  } else {
    context.body = Response.failure('删除权限失败')
  }
})
// 根据权限名称获取详情
router.post('/detail', async (context, next) => {
  const row = await getAuthorityDetail(context.request.body.name)
  if (row.name) {
    context.body = Response.success()
  } else {
    context.body = Response.failure('您当前没有该权限')
  }
})

module.exports = router
